<?php

date_default_timezone_set("Asia/Shanghai");

define('ROOT', __DIR__.DIRECTORY_SEPARATOR);
define('TOOL', ROOT.'tool'.DIRECTORY_SEPARATOR);
include(TOOL.'Dir.php');
//include($tool.'Parser.php');
include(TOOL.'Parsedown.php');
include(TOOL.'Menu.php');

$srcDir = ROOT.'src'; //待编译目录
$disDir = ROOT.'_book'; //编译后文件存放目录
$html = ROOT.'main.html'; //html框架文件

//==============获取上次编译时间
$compileLog = array();
$lastCompileTimeFile = ROOT.'last_compile_time.log'; //存放了上次编译时间
if (file_exists($lastCompileTimeFile)) {
    $lastCompileTime = json_decode(file_get_contents($lastCompileTimeFile), TRUE);
} else {
    $lastCompileTime = array();
}

//==============获取html模板, 把编译后的html嵌套到里边, 组装成完整的html页面
$tplHtml = file_get_contents($html);

//获取菜单字符串
$menu = Menu::getMenu($srcDir, 'Title');
$classChain = Menu::$nodeClassChain;
//file_put_contents('./log.log', $menu);

//==============编译md文件
//$parser = new Parser(); //sf官方的解析类, 对于单行多个 <br> 的情况, 会间隔识别
$parser = new Parsedown(); // http://parsedown.org/
$fileList = Dir::ini($srcDir)->extension('md')->fileList;

$currentTime = time();
$currentDate = date('Y-m-d H:i');
$compiledFile = array(); //本次编译的文件
foreach ($fileList as $k => $srcPathName) {
	
    $fileInfo = new SplFileInfo($srcPathName);
    //获取文件最新更新时间
	$srcFileModifyTime = $fileInfo->getMTime(); //修改时间
    $srcFileCreateTime = $fileInfo->getCTime(); //创建时间, 复制生成的文件其创建时间 > 修改时间
    $srcFileAccessTime = $fileInfo->getATime(); //文件上次访问时间
    $lastModifyTime = $srcFileCreateTime > $srcFileModifyTime ? $srcFileCreateTime : $srcFileModifyTime;
    
    // 如果上次没有编译这个文件, 或者最新修改时间大于上次编译时间就重新编译, 并记录本次编译的时间
	if ((empty($lastCompileTime[$srcPathName]) || $lastCompileTime[$srcPathName] < $lastModifyTime)) {
		$text = file_get_contents($srcPathName);
//		$markdown = $parser->makeHtml($text);
		$markdown = $parser->text($text);
        
        $arrTarget = array('{sidebar}', '{markdown}', '{modify_time}', '{class_chain}');
        $arrReplace = array($menu, $markdown, $currentDate, json_encode($classChain));
        $content = str_replace($arrTarget, $arrReplace, $tplHtml); //菜单和主要内容
		
		$disPathName = str_replace(array($srcDir, '.md'), array($disDir, '.html'), $srcPathName);
        $disPathName = Menu::trimOrder($disPathName);
		
		$dirName = dirname($disPathName);
		if (!file_exists($dirName)) {
			mkdir($dirName, 0777, true);
		}
		
		file_put_contents($disPathName, $content);
		$compiledFile[] = $disPathName;
        
        $compileLog[$srcPathName] = $currentTime;
	} else {
	    $compileLog[$srcPathName] = $lastCompileTime[$srcPathName];
    }
}

//===============记录本次编译时间
file_put_contents($lastCompileTimeFile, json_encode($compileLog, JSON_UNESCAPED_UNICODE));

//==================打印本次编译的文件列表
echo "compiled files: ".PHP_EOL;
print_r($compiledFile);

//=================删掉目标文件夹多余的文件
$disFileList = Dir::ini($disDir)
    ->extension('html')
    ->replace($disDir, '');
$srcFileList = Dir::ini($srcDir)
    ->extension('md')
    ->replace('md', 'html')
    ->replace($srcDir, '')
    ->pregReplace('_\d+_', '');
$diff = array_diff($disFileList->fileList, $srcFileList->fileList); //找到_book中多余的文件

//file_put_contents('./a.log', var_export($srcFileList->fileList, TRUE));
//file_put_contents('./b.log', var_export($disFileList->fileList, TRUE));

echo "deleted files: ".PHP_EOL;
print_r($diff);

//foreach ($diff as $v) {
//    $diffFile = $disDir.DIRECTORY_SEPARATOR.$v.'.html';
//    unlink($diffFile); //删除目录文件夹中多余的文件
//}

//删除空文件夹
//todo

echo 'over~';